#!/usr/bin/python
#coding=utf8

import requests

class WeatherUtil(object):

    class CityInfo(object):
        def __init__(self, city_info: dict = {}) -> None:
            super().__init__()
            self.weaid = city_info.get("weaid")
            self.citynm = city_info.get("citynm")
            self.cityno = city_info.get("cityno")
            self.cityid = city_info.get("cityid")
            self.area_1 = city_info.get("area_1")
            self.area_2 = city_info.get("area_2")
            self.area_3 = city_info.get("area_3")


    def __init__(self) -> None:
        super().__init__()
        self.city_info_dict =  self.query_city_infos()


    """
    查询所有城市信息
    :return: 成功返回{"citynm":city_info, ...}, 否则返回 {}
    """
    def query_city_infos(self) -> dict:
        url = 'http://api.k780.com:88/?app=weather.city&format=json'
        try:
            city_info_dict = {}
            r = requests.get(url).json()
            if '1' == r.get('success'):
                result = r.get('result')
                for value in result.values():
                    city_info = self.CityInfo(value)
                    city_info_dict[city_info.citynm] = city_info
            return city_info_dict
        # 为了防止服务器没有正常响应导致程序异常退出，这里用try-except捕获了异常
        # 如果服务器没能正常交互（返回非json或无法连接），那么就会进入下面的return
        except:
            # 将会返回一个空的字典
            return city_info_dict


    """
    获得某个城市的信息
    :param text: 城市名称 or 城市名称全拼 or 城市id or 城市顺序
    :return: 成功返回city_info, 否则返回空的 CityInfo
    """
    def get_city_info(self, text) -> CityInfo:
        city_info = self.CityInfo()
        if None != text and 0 != len(text):
            for key, value in self.city_info_dict.items():
                if key == text or value.cityid == text or value.cityno == text or value.weaid == text:
                    city_info = value
                    break
        return city_info


    def get_weather(self, city):
        cityid = self.get_city_info(city).cityid
        if None == cityid:
            return None
        url = 'http://www.weather.com.cn/data/sk/%s.html' % cityid
        r = requests.get(url).json()
        return r


    def get_now_weather(self, city):
        cityid = self.get_city_info(city).cityid
        if None == cityid:
            return None
        url = 'http://www.weather.com.cn/data/sk/%s.html' % cityid
        r = requests.get(url).json()
        return r


util = WeatherUtil()
print(util.get_now_weather("1"))